let express = require('express')
const cron = require('node-cron');
const app = express();
let bodyParser = require('body-parser')
let order = require('./controller/order_controller')
let saler = require('./controller/saler_controller')
let dealer = require('./controller/dealer_controller')
const cors = require('cors');
const path = require('path')
var multer = require('multer');
var xlstojson = require("xls-to-json-lc");
var xlsxtojson = require("xlsx-to-json-lc");
const xlsx = require('xlsx');
const port = 80;



app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'uploads')));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

// app.get('/', (req, res) => {
//     res.sendFile('./public/B2BCollecting.html', { root: __dirname });
//     // return res.send('Received a GET HTTP method');
// });

// app.get('/B2CCollecting', (req, res) => {
//     res.sendFile('./public/B2CCollecting.html', { root: __dirname });
//     // return res.send('Received a GET HTTP method');
// });

app.post('/saler/add',(req,res) => {
   let result = saler.add(req.body)
   result.then(result => {
    if(result){
        res.json({
            code: 200,
            msg: "添加成功",
            data: req.body
        })
    }else{
        res.json({
            code: 500,
            msg: "添加失败",
            data:{}
        })
    }
   }).catch(error => {
    res.json({
        code: 500,
        msg: error.sqlMessage
    })
   })
})



var storage = multer.diskStorage({ //multers disk storage settings
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + 'uploadperday' + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
    }
});
var upload = multer({ //multer settings
                storage: storage
            }).single('file');

app.post('/uploadperday', function(req, res){
    var exceltojson; //Initialization
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            //start convert process
            /** Check the extension of the incoming file and
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path, //the same path where we uploaded our file
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    }
                    let result2 = dealer.addPerdayList(result);
                    result2.then(result => {
                        if(result.affectedRows){
                            res.json({
                                code: 200,
                                msg: "添加成功",
                                data:result
                            })
                        }else{
                            res.json({
                                code: 500,
                                msg: "添加失败",
                                data:{}
                            })
                        }
                    }).catch(error => {
                        res.json({
                            code: 500,
                            msg: error.sqlMessage
                        })
                    })
                });
            } catch (e){
                res.json({
                    code: 500,
                    msg: "上传更新失败",
                    data:{}
                })
            }
        });
});

app.post('/uploadpermonth', function(req, res){
    var exceltojson; //Initialization
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            //start convert process
            /** Check the extension of the incoming file and
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path, //the same path where we uploaded our file
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    }
                    let result2 = dealer.addPerMonthList(result);
                    result2.then(result => {
                        if(result.affectedRows){
                            res.json({
                                code: 200,
                                msg: "添加成功",
                                data:result
                            })
                        }else{
                            res.json({
                                code: 500,
                                msg: "添加失败",
                                data:{}
                            })
                        }
                    }).catch(error => {
                        res.json({
                            code: 500,
                            msg: error.sqlMessage
                        })
                    })
                });
            } catch (e){
                res.json({
                    code: 500,
                    msg: "上传更新失败",
                    data:{}
                })
            }
        });
});

app.post('/dealer/add', (req, res) => {
    let result = dealer.add(req.body);
    result.then(result => {
        if(result.affectedRows){
            res.json({
                code: 200,
                msg: "添加成功",
                data:{...req.body}
            })
        }else{
            res.json({
                code: 500,
                msg: "添加失败",
                data:{}
            })
        }
    }).catch(error => {
        res.json({
            code: 500,
            msg: error.sqlMessage
        })
    })
})

app.post('/dealer/addPerdayData', (req, res) => {
    let result = dealer.addPerdayData(req.body);
    result.then(result => {
        if(result.affectedRows){
            res.json({
                code: 200,
                msg: "添加成功",
                data:{...req.body}
            })
        }else{
            res.json({
                code: 500,
                msg: "添加失败",
                data:{}
            })
        }
    }).catch(error => {
        res.json({
            code: 500,
            msg: error.sqlMessage
        })
    })////3333
})

app.get('/dealer/dealerSaleList', (req, res) => {
    let result = dealer.dealerSaleList(req.body);
    result.then(result => {
        let jsonList = JSON.parse(JSON.stringify(result))
        let arrayWorkSheet = xlsx.utils.json_to_sheet(jsonList);
        let workBook = {
            SheetNames: ['arrayWorkSheet'],
            Sheets: {'arrayWorkSheet': arrayWorkSheet}
          };
        xlsx.writeFile(workBook, path.join(__dirname,'public/data.xlsx'));
        if(result){
            res.json({
                code: 200,
                msg: "查询成功",
                url: 'http://1.117.108.166/data.xlsx',
                data:result
            })
        }else{
            res.json({
                code: 500,
                msg: "添加失败",
                data:{}
            })
        }
    }).catch(error => {
        res.json({
            code: 500,
            msg: error.sqlMessage
        })
    })
})


app.post('/order/add', (req, res) => {
    let result = order.add(req.body)
    result.then(result=>{
        if(result.affectedRows){
                res.json({
                    code: 200,
                    msg: "添加成功",
                    data:{...req.body}
                })
        }else{
                res.json({
                    code: 500,
                    msg: "添加失败",
                    data:{}
                })
            }
        }).catch(error => {
            res.json({
                code: 500,
                msg: error.sqlMessage
            })
        })
});

app.post('/list', (req, res) => {
    let result = order.list(req.body)
    result.then(data=>{
        res.json({
            code: 200,
            msg: "查询成功",
            data:data
        })
    }).catch(error => {
        res.json({
            code: 500,
            msg: error.sqlMessage
        })
    })
});


const getList = () => {
    let result = dealer.dealerSaleList('');
    result.then(result => {
        let jsonList = JSON.parse(JSON.stringify(result))
        let arrayWorkSheet = xlsx.utils.json_to_sheet(jsonList);
        let workBook = {
            SheetNames: ['arrayWorkSheet'],
            Sheets: {'arrayWorkSheet': arrayWorkSheet}
          };
        xlsx.writeFile(workBook, path.join(__dirname,'public/data.xlsx'));
        if (result) {
            const currentTime = new Date().toLocaleDateString();
            sendMail(`${currentTime} fetch data successfully`)
        } else {
            sendMail(`${currentTime} failed to fetch data `)
        }
    }).catch(error => {
        sendMail(`${currentTime} failed to fetch data `)
    })
}

const sendMail = (content) => {
    var spawn = require("child_process").spawn;
    var process = spawn('python3',["./sendmail.py",'jessica.lee@mmd-p.com',content]);
    process.stdout.on('data', function(data) {
        console.log(data.toString());
    })
    process.stdout.on('close', function (code, signal) {
        console.log('child process exited with ' +
                    `code ${code} and signal ${signal}`);
    });
}

app.listen(port, () => {
    console.log(`Hello world app listening on port ${port}!`)
    let scheduleString = '00 00 10 * * *'
    // scheduleString = '1 * * * * *'
    const task = cron.schedule(scheduleString, () => {
        console.log('start send mail');
        getList()
      });
    task.start();
});




module.exports = app